package com.wang.tasker.core;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TaskContext {
	
	private Task currentTask;
	
	private TaskPackage packet;
	
	private String workPath;
	
	private TaskExpression expression;
	
//	private Document confDom;
	
	private ConfigElement configEle;
	
	private static GlobalConfig config;
	
	private static Logger logger = LoggerFactory.getLogger(TaskContext.class);

	static {
		logger.info("Prepare environment...");
		config = new GlobalConfig();
		try {
			config.init();
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}
	
	public TaskContext(TaskPackage packet, ConfigElement configEle){
		this.packet = packet;
		this.configEle = configEle;
		expression = new TaskExpression(this);
	}
	

	public Task getCurrentTask() {
		return currentTask;
	}

	public void setCurrentTask(Task currentTask) {
		this.currentTask = currentTask;
	}

	public String getWorkPath() {
		return workPath;
	}

	public void setWorkPath(String workPath) {
		this.workPath = workPath;
	}

	public TaskPackage getPackage() {
		return packet;
	}

	public TaskExpression getExpression() {
		return expression;
	}

	public ConfigElement getConfing() {
		return this.configEle;
	}

	public Task getTask(String taskType) {
		ConfigElement typeEle = this.configEle.selectSingleElement("//TaskType/Type[@Name='" + taskType + "']");
		if(typeEle != null){
			return TaskFactory.getTaskByClass(typeEle.attributeValue("Class"));
		}
		return TaskFactory.getTaskByType(taskType);
	}
	
	public ConfigElement getShareConfig(String refName){
		ConfigElement ele = this.configEle.selectSingleElement("//ConfigManagement/Config[@Name='" + refName + "']");
		if(ele == null){
			ele = config.getShareConfig(refName);
		}
		return ele;
	}
	
	
	
	
}
